package com.zkj.filter;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 解决请求乱码问题
 * 
 * post
 * 
 * get
 * 
 * @author zkj
 * 
 */
public class EncoderFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		req.setCharacterEncoding("utf-8");// 解决post提交乱码（必须放在第一句)

		// post请求
		String postPara = req.getParameter("post");
		System.out.println(postPara);
		final HttpServletRequest request = (HttpServletRequest) req;
		HttpServletRequest proxy = (HttpServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(),
				req.getClass().getInterfaces(), new InvocationHandler() {
					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						// 请求方式
						if (request.getMethod().equalsIgnoreCase("get")) {
							if (method.getName().equals("getParameter")) {
								String value = (String) method.invoke(request, args);
								value = new String(value.getBytes("iso8859-1"), "utf-8");
								return value;
							} else {

								return method.invoke(request, args);
							}

						} else {
							// post请求方式已处理
							return method.invoke(request, args);

						}

					}
				});
		// get请求
		String getPara = proxy.getParameter("name");
		System.out.println("get请求：" + getPara);
		// chain.doFilter(req, resp);

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
